//
//  PersonalProfileHeaderView.m
//  ChatForHot
//
//  Created by wr on 2018/10/13.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "PersonalProfileHeaderView.h"
#import "HOTCHATClipViewController.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>

@interface PersonalProfileHeaderView ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,ClipViewControllerDelegate>

@property (nonatomic, strong) UIImageView *HOTCHATavatarPickView;
@property (nonatomic, strong) UILabel *HOTCHATnickNameTitleLabel;
@property (nonatomic, strong) UITextField *HOTCHATnameInputTextField;
@property (nonatomic, strong) UILabel *HOTCHATinrtoLable;
@property (nonatomic, strong) UIView *HOTCHATintroView;
@property (nonatomic, strong) UIView *HOTCHATlineView;
@property (nonatomic, strong) UIView *HOTCHATnickeNameLineView;

@property (nonatomic, strong, readwrite) RACSubject *introDidSelectSubject;
@end

@implementation PersonalProfileHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self HOTCHATdidInitialized];
    }
    return self;
}

- (void)HOTCHATdidInitialized {
    
    self.introDidSelectSubject = [RACSubject subject];
    
    self.HOTCHATavatarPickView = [[UIImageView alloc] init];
    self.HOTCHATavatarPickView.layer.masksToBounds = YES;
    self.HOTCHATavatarPickView.layer.cornerRadius = 45;
    [self addSubview:self.HOTCHATavatarPickView];
    
    @weakify(self)
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        @strongify(self)
        [self HOTCHATAvatarClick];
    }];
    self.HOTCHATavatarPickView.userInteractionEnabled = YES;
    [self.HOTCHATavatarPickView addGestureRecognizer:tap];
    
    self.HOTCHATnickNameTitleLabel = [[UILabel alloc] init];
    self.HOTCHATnickNameTitleLabel.textColor = [UIColor colorFromHexString:@"111111"];
    self.HOTCHATnickNameTitleLabel.font = [UIFont systemFontOfSize:15];
    self.HOTCHATnickNameTitleLabel.text = NSLocalizedString(@"profileHe1", nil);
    [self addSubview:self.HOTCHATnickNameTitleLabel];
    
    self.HOTCHATnameInputTextField = [[UITextField alloc] init];
    self.HOTCHATnameInputTextField.textColor = [UIColor colorFromHexString:@"111111"];
    self.HOTCHATnameInputTextField.font = [UIFont systemFontOfSize:16];
    self.HOTCHATnameInputTextField.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.HOTCHATnameInputTextField];
    
    [self.HOTCHATnameInputTextField.rac_textSignal subscribeNext:^(NSString *text) {
        @strongify(self)
        self.model.nickName = text;
    }];
    
    
    self.HOTCHATinrtoLable = [[UILabel alloc] init];
    self.HOTCHATinrtoLable.textColor = [UIColor colorFromHexString:@"111111"];
    self.HOTCHATinrtoLable.font = [UIFont systemFontOfSize:16];
    self.HOTCHATinrtoLable.text = NSLocalizedString(@"profileHe2", nil);
    [self addSubview:self.HOTCHATinrtoLable];
    
    self.HOTCHATintroView = [[UIView alloc] init];
    self.HOTCHATintroView.layer.masksToBounds = YES;
    self.HOTCHATintroView.layer.borderColor = [UIColor colorFromHexString:@"#B9B9B9"].CGColor;
    self.HOTCHATintroView.layer.borderWidth = PixelOne;
    self.HOTCHATintroView.layer.cornerRadius = 5;
    self.HOTCHATintroView.backgroundColor = [UIColor colorFromHexString:@"#F4F4F4"];
    [self addSubview:self.HOTCHATintroView];
    
    UITapGestureRecognizer *introTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        @strongify(self)
        [self.introDidSelectSubject sendNext:nil];
    }];
    self.HOTCHATintroView.userInteractionEnabled = YES;
    [self.HOTCHATintroView addGestureRecognizer:introTap];
    
    self.HOTCHATinrtoMesgLabel = [[YYLabel alloc] init];
    self.HOTCHATinrtoMesgLabel.textColor = HOTCHATrgb(179, 179, 179);
    self.HOTCHATinrtoMesgLabel.font = [UIFont systemFontOfSize:10];
    self.HOTCHATinrtoMesgLabel.textAlignment = NSTextAlignmentLeft;
    self.HOTCHATinrtoMesgLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
    [self.HOTCHATintroView addSubview:self.HOTCHATinrtoMesgLabel];
    
    self.HOTCHATlineView = [[UIView alloc] init];
    self.HOTCHATlineView.backgroundColor = [UIColor colorFromHexString:@"#EEEEEE"];
    [self addSubview:self.HOTCHATlineView];
    
    self.HOTCHATnickeNameLineView = [[UIView alloc] init];
    self.HOTCHATnickeNameLineView.backgroundColor = [UIColor colorFromHexString:@"#EEEEEE"];
    [self addSubview:self.HOTCHATnickeNameLineView];
}

- (void)setModel:(UserInfoModel *)model {
    _model = model;
    self.HOTCHATnameInputTextField.text = self.model.nickName;
    
    self.HOTCHATinrtoMesgLabel.text = [self.model.signature isEqualToString:@""] ? NSLocalizedString(@"profileHe4", nil) :self.model.signature;
    
    if (![self.model.headPic isEqualToString:@""]) {
        [self.HOTCHATavatarPickView simple_setImageWithURL:[NSString stringWithFormat:@"%@%@",APIHEADER,self.model.headPic] placeholderImage:[UIImage imageNamed:@"personal_atatar_but_n"]];
    }else {
        [self.HOTCHATavatarPickView setImage:[UIImage imageNamed:@"personal_atatar_but_n"]];
    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.HOTCHATavatarPickView.size = CGSizeMake(90, 90);
    self.HOTCHATavatarPickView.top = 50;
    self.HOTCHATavatarPickView.centerX = self.centerX;
    
    self.HOTCHATnickNameTitleLabel.size = CGSizeMake(77, 21);
    self.HOTCHATnickNameTitleLabel.top = 186;
    self.HOTCHATnickNameTitleLabel.left = 38;
    
    self.HOTCHATnameInputTextField.size = CGSizeMake(150, 21);
    self.HOTCHATnameInputTextField.centerY = self.HOTCHATnickNameTitleLabel.centerY;
    self.HOTCHATnameInputTextField.left = self.HOTCHATnickNameTitleLabel.right;
    
    self.HOTCHATnickeNameLineView.size = CGSizeMake(150, PixelOne);
    self.HOTCHATnickeNameLineView.top = self.HOTCHATnameInputTextField.bottom + 1;
    self.HOTCHATnickeNameLineView.left = self.HOTCHATnickNameTitleLabel.right;
    
    self.HOTCHATinrtoLable.size = CGSizeMake(35, 21);
    self.HOTCHATinrtoLable.top = self.HOTCHATnickNameTitleLabel.bottom + 15;
    self.HOTCHATinrtoLable.left = 38;
    
    self.HOTCHATintroView.size = CGSizeMake(258, 60);
    self.HOTCHATintroView.top = self.HOTCHATinrtoLable.top;
    self.HOTCHATintroView.left = self.HOTCHATinrtoLable.right + 5;
    
    self.HOTCHATinrtoMesgLabel.size = CGSizeMake(250, 60);
    self.HOTCHATinrtoMesgLabel.left = 2;
    self.HOTCHATinrtoMesgLabel.top = 2;
    
    self.HOTCHATlineView.size = CGSizeMake(kScreenWidth - 30, 2.5);
    self.HOTCHATlineView.bottom = self.bottom - 10;
    self.HOTCHATlineView.left = 15;
    
}

#pragma mark - SelectedPhotoActions

- (void)HOTCHATAvatarClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:NSLocalizedString(@"alert2", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self HOTCHATOpenCamera];
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:NSLocalizedString(NSLocalizedString(@"alert3", nil), nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self HOTCHATPopenPhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(NSLocalizedString(@"alert1", nil), nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:camera];
    [alert addAction:photo];
    [alert addAction:cancel];
    [self.viewController presentViewController:alert animated:YES completion:nil];
}

- (void)HOTCHATOpenCamera {
    self.viewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    }else{
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    [imagePicker setDelegate:self];
    
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"access2", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"clip3", nil) otherButtonTitles:nil, nil];
        alertView.tag = 100;
        [alertView show];
    }else {
        [self.viewController presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)HOTCHATPopenPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    @weakify(self)
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            if ( status == PHAuthorizationStatusAuthorized) {
                [self.viewController presentViewController:picker animated:YES completion:nil];
            }else if (status == PHAuthorizationStatusDenied) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"access1", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"clip3", nil) otherButtonTitles:nil, nil];
                alertView.tag = 100;
                [alertView show];
            }
        });
    }];
    
}

#pragma mark - <UIImagePickerControllerDelegate>

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    portraitImg = [[HCHelper sharedInstance] HOTCHATimageCompressToMaxSize:portraitImg];
    // 裁剪
    HOTCHATClipViewController *clipView = [[HOTCHATClipViewController alloc] initWithImage:portraitImg];
    clipView.delegate = self;
    clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
    clipView.radius = 150;   //设置 裁剪框的半径  默认120
    clipView.scaleRation = 3;//图片缩放的最大倍数
    clipView.isCamera = (picker.sourceType == UIImagePickerControllerSourceTypeCamera);
    [picker pushViewController:clipView animated:YES];
}

#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(HOTCHATClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self HOTCHATuploadActionImg:editImage];
        [clipViewController dismissViewControllerAnimated:YES completion:^{
        }];
    });
}

- (void)HOTCHATuploadActionImg:(UIImage *)img{
    @weakify(self)
    [(BaseViewController *)self.viewController HOTCHATstartLoading];
    
    NSMutableDictionary *mparameters = [[NSMutableDictionary alloc] init];
    [mparameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
    
    [NetWorkTool HOTCHATUploadImageData:UPLOADHEADPIC_URL parameters:mparameters fileData:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:img.HOTCHATcompressQualityData name:@"uploadfile" fileName:@"headpic.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSString * _Nonnull HOTCHATmsgCode, NSDictionary * _Nonnull HOTCHATresultDic) {
        @strongify(self)
        [(BaseViewController *)self.viewController HOTCHATstopLoading];
        if ([HOTCHATmsgCode isEqualToString:@"0"]) {
            NSString *dataurl = [HOTCHATresultDic valueForKey:@"data"];
            if (dataurl.length > 0) {
                NSString *fullURL = [NSString stringWithFormat:@"%@%@",APIHEADER,dataurl];
                YYImageCache *cache = [YYImageCache sharedCache];
                [cache setImage:img forKey:fullURL];
                self.HOTCHATavatarPickView.image = img;
                self.HOTCHATavatarPickView.contentMode = UIViewContentModeScaleAspectFill;
                self.model.headPic = fullURL;
                [APPINFO defaultManager].headPic = fullURL;
            }
        }
        if ([HOTCHATmsgCode isEqualToString:@"1"]) {
            NSString *message = [HOTCHATresultDic valueForKey:@"message"];
            if (message.length > 0) {
                [NetWorkTool HOTCHATshowMessage:message];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSError * _Nonnull error) {
        @strongify(self)
        [(BaseViewController *)self.viewController HOTCHATstopLoading];
    }];
}
@end
